# coding: utf-8
# 定义验证码功能
import configparser

from PIL import Image
from PIL import ImageFont
from PIL import ImageDraw
from PIL import ImageFilter
import pytesseract
import random
import os


class VerifyCode:
    def __init__(self):
        self.base_dir = 'ext/E1_generate_code'
        self.chars = 'abcdefghijklmnopqrstuvwxyz123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
        _user_pswd_cfg = os.environ['user_pswd']
        _cf = configparser.ConfigParser()
        _cf.read(_user_pswd_cfg)
        self.font = _cf.get('path', 'ttf_MSYH')

    # 绘制随机字符
    def generate_random_string(self):
        # 随机产生４个不同字符
        random_chars = "".join(random.sample(self.chars, 4))
        print(random_chars)
        return random_chars

    # 获得图片背景颜色
    def draw_disturb_point(self, pen_for_image):
        for _ in range(100):
            # 随机生成干扰点位置
            pos = (random.randint(0, 100), random.randint(0, 30))
            # 随机生成点的颜色
            color = (random.randint(0, 255), 255, random.randint(0, 255))
            # 将点绘制到图片上
            pen_for_image.point(pos, color)

    # 给图片绘制随机文字
    def draw_random_string(self, pen_for_image, random_string):
        # 加载字体
        my_font = ImageFont.truetype(self.font, 16)
        # 设置字符颜色
        # my_color = (255, random.randrange(0, 255), random.randrange(0, 255))
        my_color = (0, 0, 0)
        # 绘制字符
        for number, ch in enumerate(random_string):
            pen_for_image.text((5 + number * 20, 2), ch, my_color, my_font)

    # 绘制基本图片
    def create_base_image(self):
        # 定义图片背景颜色(RGB)
        # bg_color = (random.randrange(20, 100), random.randrange(20, 100), 255)
        bg_color = (255, 255, 255)
        # 创建图片, 分别设置图片格式, 图片大小, 图片背景颜色
        verify_image = Image.new('RGB', (100, 30), bg_color)

        return verify_image

    # 随机图片视图函数
    def verification_code(self):
        # 生成随机字符序列
        random_string = self.generate_random_string()
        # 创建图片对象
        verify_image = self.create_base_image()
        # 创建对图片(verify_image)的画笔
        pen_for_image = ImageDraw.Draw(verify_image)
        # 将随机字符绘制到图片上
        self.draw_random_string(pen_for_image, random_string)
        # 绘制图片干扰点
        # self.draw_disturb_point(pen_for_image)
        # 模糊处理
        # verify_image = verify_image.filter(ImageFilter.BLUR)
        # print(image_data)
        return random_string, verify_image

    def save(self):
        for i in range(1, 10):
            _, vc = self.verification_code()
            image = '{}/g00{}_image.jpg'.format(self.base_dir, str(i))
            vc.save(image, 'jpeg')

    # 验证匹配率
    def match_str(self, filename):
        _rs, _vc = self.verification_code()
        _image = '{}/{}'.format(self.base_dir, filename)
        _vc.save(_image, 'jpeg')
        _im = Image.open(_image)
        _im = _im.convert('P')
        _data = ''.join([_item for _item in pytesseract.image_to_string(_im) if _item != ' '])
        return _rs.upper() == _data.upper()

    def count_success(self, times=10):
        _count = 0
        for i in range(times):
            if self.match_str(filename='v_image.jpg'):
                _count += 1
        print(_count / times)


def main():
    vc = VerifyCode()
    # vc.save()
    vc.count_success()


if __name__ == '__main__':
    main()
